package com.qzsoft.jeemis.common.typehandle;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;

/**
 * @ClassName JsonArrayHandler
 * @Description json数组与字符串转化
 * @author linhuawei
 * @since 2022-01-26
 */
public class JsonArrayHandler extends BaseTypeHandler<JSONArray> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, JSONArray parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setString(i, cover(parameter));
    }

    @Override
    public JSONArray getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return cover(rs.getString(columnName));
    }

    @Override
    public JSONArray getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return cover(rs.getString(columnIndex));
    }

    @Override
    public JSONArray getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return cover(cs.getString(columnIndex));
    }

    private JSONArray cover(String str) {
        JSONArray array = null;
        if (ObjectUtils.isNotEmpty(str)) {
            try {
                array = JSON.parseArray(str);
            } catch (Exception e) {
                array = null;
            }
        }
        return array;
    }
    
    private String cover(JSONArray array) {
        if(null == array || 0 == array.size()) {
            return null;
        }
        return array.toJSONString();
    }

}
